package com.cn.zhongxj.jetpack.ui

import android.util.Log
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.cn.zhongxj.jetpack.R
import com.cn.zhongxj.jetpack.ui.model.SearchHistoryState

@Composable
fun SearchPage(
    searchHistoryList: MutableList<SearchHistoryState>,
    onBackClick: () -> Unit,
    onSearchTrigger: (String) -> Unit,
    onClearAllClick: () -> Unit,
    onDeleteClick: (SearchHistoryState) -> Unit,
    onHistoryItemClick: (SearchHistoryState) -> Unit
) {
    Column(
        modifier = Modifier.fillMaxSize()
            .background(Color.White)
            .padding(
                start = 15.dp,
                end = 15.dp
            )
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .height(50.dp),
            horizontalArrangement = Arrangement.Center,
            verticalAlignment = Alignment.CenterVertically
        ) {
            // back button
            IconButton(onClick = { onBackClick() }, modifier = Modifier.size(40.dp)) {
                Icon(
                    painter = painterResource(
                        R.drawable.ic_browser_back
                    ),
                    contentDescription = null
                )
            }
            Spacer(modifier = Modifier.width(5.dp).fillMaxHeight())
            // search box
            SearchBox(onStartSearch = { url ->
                onSearchTrigger(url)
            })
        }

        // history list head
        Spacer(
            modifier = Modifier
                .fillMaxWidth()
                .height(10.dp)
        )
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .height(20.dp)
        ) {
            Box(
                modifier = Modifier
                    .weight(1f)
                    .wrapContentHeight(),
                contentAlignment = Alignment.CenterStart
            ) {
                Text(
                    text = "近期浏览", style = TextStyle(
                        fontSize = 15.sp,
                        color = Color(0xFF272729),
                        fontWeight = FontWeight.Bold,
                        textAlign = TextAlign.Center
                    )
                )
            }

            Box(
                modifier = Modifier.weight(1f).fillMaxHeight(),
                contentAlignment = Alignment.CenterEnd
            ) {
                Text(
                    text = "全部清空",
                    style = TextStyle(
                        fontSize = 13.sp,
                        color = Color(0x99676773),
                        fontWeight = FontWeight.Normal,
                        textAlign = TextAlign.Center
                    ),
                    modifier = Modifier.clickable(
                        indication = null,
                        interactionSource = remember {
                            MutableInteractionSource()
                        }) { onClearAllClick() },
                )
            }
        }

        Spacer(modifier = Modifier.fillMaxWidth().height(20.dp))
        // history list
        val listState = rememberLazyListState()
        val context = LocalContext.current
        LazyColumn(
            state = listState,
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.spacedBy(10.dp),
            modifier = Modifier.height(221.dp)
        ) {
            items(searchHistoryList) { searchHistoryState ->
                key(searchHistoryState.history_id) {
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(37.dp)
                    ) {
                        Box(
                            modifier = Modifier.fillMaxHeight().weight(9f)
                                .clickable(indication = null,
                                    interactionSource = remember {
                                        MutableInteractionSource()
                                    }) {
                                    onHistoryItemClick(searchHistoryState)
                                },
                            contentAlignment = Alignment.CenterStart
                        ) {
                            Text(
                                text = searchHistoryState.history_content, style = TextStyle(
                                    fontSize = 13.sp,
                                    textAlign = TextAlign.Center,
                                    color = Color(0xFF848485),
                                    fontWeight = FontWeight.Normal
                                ),
                                overflow = TextOverflow.Ellipsis,
                                maxLines = 1
                            )
                        }

                        Box(
                            modifier = Modifier.fillMaxHeight().weight(1f),
                            contentAlignment = Alignment.CenterEnd
                        ) {
                            IconButton(
                                onClick = { onDeleteClick(searchHistoryState) },
                                modifier = Modifier.size(22.62.dp)
                            ) {
                                Icon(
                                    painter = painterResource(R.drawable.ic_browser_delete_history),
                                    contentDescription = null,
                                    tint = Color(0xFFA9AFB5)
                                )
                            }
                        }
                    }
                }

            }
        }
    }
}

@Composable
fun SearchBox(onStartSearch: (String) -> Unit) {
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .height(44.dp)
            .padding(top = 2.dp, bottom = 2.dp),
        contentAlignment = Alignment.Center
    ) {
        // search box
        var text by remember {
            mutableStateOf("")
        }

        // request focus obj
        val requester = remember {
            FocusRequester()
        }

        LaunchedEffect(key1 = Unit) {
            requester.requestFocus() //request focus
        }

        val context = LocalContext.current

        BasicTextField(
            value = text,
            maxLines = 1,
            singleLine = true,
            onValueChange = {
                text = it
            },
            keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
            keyboardActions = KeyboardActions(
                onDone = {
                    Log.d("zhongxj", "onDone clicked")
                },
                onGo = {
                    Log.d("zhongxj", "onGo clicked")
                },
                onSearch = {
                    onStartSearch(text)
                }
            ),
            decorationBox = { innerTextField ->
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.padding(
                        vertical = 2.dp,
                        horizontal = 3.dp
                    )
                ) {

                    // search icon

                    Box(
                        modifier = Modifier
                            .wrapContentWidth()
                            .fillMaxHeight()
                            .padding(start = 5.dp),
                        contentAlignment = Alignment.CenterStart
                    ) {
                        IconButton(
                            onClick = { text = "" },
                            modifier = Modifier.size(32.dp),
                            enabled = text.isNotEmpty()
                        ) {
                            Icon(
                                painter = painterResource(R.drawable.ic_browser_search),
                                contentDescription = null
                            )
                        }
                    }

                    // place holder
                    Box(
                        modifier = Modifier
                            .weight(8f),
                        contentAlignment = Alignment.CenterStart
                    ) {
                        if (text.isEmpty()) {
                            Text(
                                text = "输入网址或者关键词搜索",
                                style = TextStyle(
                                    fontSize = 14.sp,
                                    color = Color(0, 0, 0, 128),
                                    textAlign = TextAlign.Center

                                ),
                                overflow = TextOverflow.Ellipsis,
                                modifier = Modifier.wrapContentWidth()
                            )
                        }

                        innerTextField()
                    }

                    AnimatedVisibility(text.isNotEmpty()) {
                        Box(
                            modifier = Modifier
                                .weight(2f)
                                .fillMaxHeight()
                                .padding(start = 5.dp, end = 5.dp),
                            contentAlignment = Alignment.CenterEnd
                        ) {
                            IconButton(
                                onClick = { text = "" },
                                modifier = Modifier.size(32.dp)
                            ) {
                                Icon(
                                    painter = painterResource(R.drawable.ic_browser_delete),
                                    contentDescription = null
                                )
                            }
                        }
                    }
                }
            },
            modifier = Modifier
                .border(
                    width = 2.dp,
                    color = Color(0xFF31373D),
                    shape = RoundedCornerShape(12.dp)
                )
                .fillMaxHeight()
                .fillMaxWidth()
                .focusRequester(requester)
        )
    }
}

@Preview(showBackground = true)
@Composable
fun PreviewSearchBox() {
    SearchPage(mutableListOf(),
        onBackClick = {},
        onSearchTrigger = {},
        onClearAllClick = {},
        onDeleteClick = {},
        onHistoryItemClick = {}
    )
}